home *** CD-ROM | disk | FTP | other *** search
- Path: news.iag.net!news
- From: jatmon@iag.net (John R Buchan)
- Newsgroups: comp.lang.c
- Subject: Re: pseudo-random numbers
- Date: 11 Jan 1996 17:49:51 GMT
- Organization: Internet Access Group, Orlando, Florida
- Message-ID: <4d3ijv$9fl@news.iag.net>
- References: <17709D420S86.JJSTEP00@ukcc.uky.edu>
- NNTP-Posting-Host: pm3-orl4.iag.net
- X-Newsreader: WinVN 0.99.7
-
- In article <17709D420S86.JJSTEP00@ukcc.uky.edu>, JJSTEP00@ukcc.uky.edu says...
- >
- >I know what the c.l.c. FAQ says about pseudo-random numbers, so I wonder why
- >I seem to get "better" results with "rand() % n + 1" than I get when I use
- >"n * rand() / RAND_MAX + 1" Am I missing some parenthesis or something?
-
- I don't know what type you have defined n as, but I'll bet that it is an
- integer of some type. I can see two like problems.
-
- 1. n * rand() exceeds the limits of int (the return type of rand) and/or
- n's type.
-
- 2. Integer math is being performed. So any fractional part of the answer
- is being truncated.
-
- One solution, suggested in the faq <polite jab>, is:
-
- (int)((double)rand() / ((double)RAND_MAX + 1) * N)
-
- This forces floating point math and casts the result back to an int. I'll
- leave any adjustments to you.
-
- --
- John R Buchan -:|:- Looking for that elusive FAQ? ftp to:
- jatmon@mail.iag.net -:|:- rtfm.mit.edu /pub/usenet-by-group/....
-
-